<script setup lang="ts">

defineOptions({name: 'CustomModuleField'})
import { ElMessageBox } from 'element-plus'
import {useTable} from '@/composables/useTable'
import {dateFormat, getIsMobile, formatEnumData} from "@utils/helper"
import {useI18n} from "vue-i18n"
import {getEnumData} from '@/api/enum'
import {getLanguageData} from '@/api/language'
import {getCustomModuleFieldList, deleteCustomModuleField} from '@/api/custom-module-field'
import Search from './search-field.vue'
import Create from './create-field.vue'
import Update from './update-field.vue'

const dataId = ref<number | string | undefined>(0)
const visible = ref<boolean>(false)
const isMobile = getIsMobile()
const {t} = useI18n()
const enumData = ref<any>({})
const enumDataFormat = ref<any>({})
const languageData = ref<any>({})
const sortField = new Map<string, any>()
const createRef = ref()
const updateRef = ref()

onMounted(async () => {
	await getLanguage()
	await getEnum()
})

/**
 * 表格函数
 */
const {
	columns,
	columnChecks,
	data,
	loading,
	pagination,
	updateColumn,
	searchParams,
	handleSizeChange,
	handleCurrentChange,
	resetSearchParams,
	refreshData,
	getDataDebounced,
	clearData
} = useTable({
	// 核心配置
	core: {
		apiFn: getCustomModuleFieldList,
		immediate: false,
		apiParams: {
			page: 1,
			limit: 10,
		},
		columnsFactory: () => [
			{prop: 'operate', label: t('common.operate'), width: 110, useSlot: true},
			{prop: 'labelName', minWidth: 120},
			{prop: 'fieldName', minWidth: 115},
			{prop: 'type', minWidth: 95, useSlot: true},
			{prop: 'rule', minWidth: 135},
			{prop: 'config', minWidth: 135},
			{prop: 'sort', label: t('common.field.sort'), width: 90, sortable: 'custom'},
			{
				prop: 'createTime', label: t('common.field.createTime'), width: 170, useSlot: true,
				sortable: 'custom',
			},
			{
				prop: 'updateTime', label: t('common.field.updateTime'), width: 170, useSlot: true,
				sortable: 'custom',
			}
		]
	}
})

/**
 * 获取枚举数据
 */
const getEnum = async () => {
	enumData.value = await getEnumData({modules: ['customModuleField']})
	enumDataFormat.value = formatEnumData(enumData.value)
}

/**
 * 获取语言数据
 */
const getLanguage = async () => {
	const res: any = await getLanguageData({modules: ['customModuleField']});
	languageData.value = {...res};
	for (let key in res.customModuleField.field) updateColumn?.(key, {label: res.customModuleField.field[key]})
}

/**
 * 处理排序改变
 * @param params
 */
const handleSortChange = (params: any) => {
	const hasProp = sortField.has(params.prop);
	if (hasProp && params.order === null) sortField.delete(params.prop)
	else sortField.set(params.prop, params.order)
	let orderBy: any = {};
	for (const [key, value] of sortField) if (value) orderBy[key] = value === 'ascending' ? 'asc' : 'desc'
	// 搜索参数赋值
	Object.assign(searchParams, {orders: {...orderBy}})
	getDataDebounced()
}

/**
 * 处理表头单元格的 className 的回调方法
 * @param column
 */
const handleHeaderCellClassName = ({column}: { column: any }) => {
	if (sortField.has(column.property)) column.order = sortField.get(column.property)
	return ''
}

/**
 * 处理搜索重置
 * @param filterData
 */
const handleSearchReset = (filterData: any) => {
	resetSearchParams()
	Object.assign(searchParams, {customModuleId: dataId.value})
	Object.assign(searchParams, {...filterData})
	getDataDebounced()
}

/**
 * 处理搜索确认
 * @param filterData
 */
const handleSearchConfirm = (filterData: any) => {
	resetSearchParams()
	Object.assign(searchParams, {customModuleId: dataId.value})
	Object.assign(searchParams, {...filterData})
	getDataDebounced()
}

/**
 * 处理显示创建
 */
const handleShowCreate = () => createRef.value.open(dataId.value)

/**
 * 处理显示更新
 */
const handleShowUpdate = (id: number | string) => updateRef.value.open(id)

/**
 * 处理删除
 * @param id
 */
const handleDelete = async (id: number) => {
	ElMessageBox.confirm(t('common.deleteTip'), t('common.deleteConfirm'), {
		confirmButtonText: t('common.confirm'), cancelButtonText: t('common.cancel'),
		type: 'error', draggable: true
	}).then(() => {
		loading.value = true
		deleteCustomModuleField({customModuleFieldId: id}).then(() => refreshData()).finally(() => loading.value = false)
	}).catch(() => {
	})
}

const open = (id?: number) => {
	visible.value = true
	dataId.value = id
	clearData()
	resetSearchParams()
	Object.assign(searchParams, {customModuleId: id})
	getDataDebounced()
}

const close = () => visible.value = false

defineExpose({open, close})
</script>

<template>
	<div class="custom-module-field-box">
		<ElDrawer v-model="visible" :size="isMobile ? '100%' : '80%'" :close-on-click-modal="false"
			  @close="close"
			  :title="t('module.customModule.operate.fieldConfig')">
			<div class="art-full-height">
				<!-- 搜索栏 -->
				<Search :enumData="enumData" :languageData="languageData" @reset="handleSearchReset"
					@search="handleSearchConfirm"/>

				<ElCard class="art-table-card" shadow="never">
					<!-- 表格头部 -->
					<ArtTableHeader v-model:columns="columnChecks" :loading="loading"
							@refresh="refreshData">
						<template #left>
							<ElSpace wrap>
								<ElButton v-auth="'customModuleFieldCreate'"
									  @click="handleShowCreate" v-ripple>
									{{ t('common.create') }}
								</ElButton>
							</ElSpace>
						</template>
					</ArtTableHeader>

					<!-- 表格 -->
					<ArtTable
						:loading="loading"
						:data="data"
						:columns="columns"
						:show-overflow-tooltip="true"
						:header-cell-class-name="handleHeaderCellClassName"
						:pagination="pagination"
						@pagination:size-change="handleSizeChange"
						@pagination:current-change="handleCurrentChange"
						@sort-change="handleSortChange"
					>
						<template #type="{row}">
							<template v-if="enumDataFormat.customModuleField">
								{{ enumDataFormat.customModuleField.type[row.type] }}
							</template>
						</template>
						<template #operate="{row}">
							<ArtButtonTable type="edit" v-auth="'customModuleUpdate'"
									@click="handleShowUpdate(row.customModuleFieldId)"/>
							<ArtButtonTable type="delete" v-auth="'customModuleDelete'"
									@click="handleDelete(row.customModuleFieldId)"/>
						</template>
						<template #createTime="{row}">
							{{ dateFormat(row.createTime) }}
						</template>
						<template #updateTime="{row}">
							{{ dateFormat(row.updateTime) }}
						</template>
					</ArtTable>
				</ElCard>
			</div>
		</ElDrawer>
		<Create ref="createRef" :enumData="enumData" :languageData="languageData" @success="refreshData"/>
		<Update ref="updateRef" :enumData="enumData" :languageData="languageData" @success="refreshData"/>
	</div>
</template>

<style scoped lang="scss">
.custom-module-field-box {
	:deep(.el-drawer__header) {
		margin-top: 15px;
	}

	:deep(.el-drawer__title) {
		text-align: center;
	}

	:deep(.el-drawer__body) {
		padding-top: 0;
	}

	:deep(.el-drawer__footer) {
		padding-bottom: 10px;
		border-top: 1px dotted rgba(149, 155, 156, 0.67);
	}
}
</style>